<?php
/* *
 * 支付宝接口RSA函数
 * 详细：RSA签名、验签、解密
 * 版本：3.3
 * 日期：2012-07-23
 * 说明：
 * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 * 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
 */

/**
 * RSA签名
 * @param $data 待签名数据
 * @param $private_key 商户私钥字符串
 * return 签名结果
 */
function rsaSign($data) {
    $priKey = "-----BEGIN RSA PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALVBpvNt3yELu/odjbdr82PtOQdGz6NbtfgqQ47RGORKrtr3pFrvGMKG00oSO5L0CO+WG1jS6asAfLLVgT9sQCFuG8UuAKVrM5O6pt929uIqZHbAjNph5rs7H5gJ//tFJnALdgtgzi9tbJFzsihndiO8cCr2nLNH9qHfmP8sA3yzAgMBAAECgYA+G1jRYHxsHlEyyp2ck+i5/Lblv2W2W95mQlUTwqH813pCnUg7wGGDhh8v6j9vgx7suUp1jQ90AJ65yF6ZFMaEGaEfS+SYRpeaNiRQWPb9lQBN8oLTlWWg6YdafcTGEYFI6d2eSJCvzY7Efr9oNhgp9Ho1p5GCklY6ecercNIzQQJBAO0dqlz7Qg7UYjMIVIgllWvxBII+keVFeY7BZtXwLvoK668HmP9AHipGhsk56sDBt3ZY7NodPkZjmIqcCfze7hcCQQDDsR70XM1Mr8488V67S/sqRi1a175/cXyZNnlgNg77Cm9ZWOv43lHaMWsX3arwHfECSAK4L9CHFTdMBqgdNAPFAkBThNt5HNdLuetM5mY//lz/REm+RqPFCg+jBORf/tXNJQOXByoQ3ljBs03OmyPg+VrRyMjEmwBQcsxMJmIuO6fJAkBF89Ov4FiW+CVODa4iX7fJ1coytfpnziaPEjTzGn/iZ0mEc8/uZ3J0/8NbhaasLNfRS/KE6rqs/v2EVMDVp5lNAkBLv3Jruwg8f6PjBQ2R5HZUZaSTXRvvOcf5O9zTltuAZs0hDGtsF0cMDZZAw7a160V9yBWONUEvr3WUwq184b/Q
-----END RSA PRIVATE KEY-----";
    $res = openssl_get_privatekey($priKey);
    openssl_sign($data, $sign, $res);
    openssl_free_key($res);
    $sign = base64_encode($sign);
    $sign = urlencode($sign);
    return $sign;
}
function rsaSign1($data, $private_key) {
    //以下为了初始化私钥，保证在您填写私钥时不管是带格式还是不带格式都可以通过验证。
    $private_key=str_replace("-----BEGIN RSA PRIVATE KEY-----","",$private_key);
	$private_key=str_replace("-----END RSA PRIVATE KEY-----","",$private_key);
	$private_key=str_replace("\n","",$private_key);

	$private_key="-----BEGIN RSA PRIVATE KEY-----".PHP_EOL .wordwrap($private_key, 64, "\n", true). PHP_EOL."-----END RSA PRIVATE KEY-----";

    $res=openssl_get_privatekey($private_key);

    if($res)
    {
        openssl_sign($data, $sign,$res);
    }
    else {
        echo "您的私钥格式不正确!"."<br/>"."The format of your private_key is incorrect!";
        exit();
    }
    openssl_free_key($res);
	//base64编码
    $sign = base64_encode($sign);
    return $sign;
}

/**
 * RSA验签
 * @param $data 待签名数据
 * @param $alipay_public_key 支付宝的公钥字符串
 * @param $sign 要校对的的签名结果
 * return 验证结果
 */
function rsaVerify($data, $alipay_public_key, $sign)  {
    try{
//以下为了初始化私钥，保证在您填写私钥时不管是带格式还是不带格式都可以通过验证。
        /*$alipay_public_key=str_replace("-----BEGIN PUBLIC KEY-----","",$alipay_public_key);
        $alipay_public_key=str_replace("-----END PUBLIC KEY-----","",$alipay_public_key);
        $alipay_public_key=str_replace("\n","",$alipay_public_key);
        $alipay_public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
        $alipay_public_key='-----BEGIN PUBLIC KEY-----'.PHP_EOL.wordwrap($alipay_public_key, 64, "\n", true) .PHP_EOL.'-----END PUBLIC KEY-----';*/
        $fp = fopen ($alipay_public_key, "r");
        $alipay_public_key = fread ($fp, filesize ($alipay_public_key));
        fclose ($fp);
        //logfile('$alipay_public_key:'.print_r($alipay_public_key,1),'lalipay');
        $res=openssl_get_publickey($alipay_public_key);
        if($res)
        {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res);
            //logfile('res2:'.json_encode($result),'lalipay');
            //logfile('openssl_error_string:'.json_encode(openssl_error_string()),'lalipay');
        }
        else {
            echo "您的支付宝公钥格式不正确!"."<br/>"."The format of your alipay_public_key is incorrect!";
            exit();
        }
        openssl_free_key($res);
    } catch(Exception $e) {
        logfile('$e:'.json_encode($e),'lalipay');
    }

    return $result;
}

?>